package com.spark.incoicings.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.incoicings.dao.ProductMapper;
import com.spark.incoicings.dao.PurchaseDetailsMapper;
import com.spark.incoicings.service.ProductService;
import com.spark.incoicings.utils.RandomGenerateUtil;
import com.spark.invoicings.entity.Code;
import com.spark.invoicings.entity.Product;
import com.spark.invoicings.entity.PurchaseDetail;
import com.spark.invoicings.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private RandomGenerateUtil randomGenerateUtil;

    @Resource
    private PurchaseDetailsMapper purchaseDetailMapper;

    @Override
    public Product selectPurchaseProductById(Integer id) {
        return productMapper.selectPurchaseProductById(id);
    }

    @Override
    public Product selectProductByPId(Integer id) {
        return productMapper.selectProductById(id);
    }

    /**
     * 添加产品
     * @param product
     * @return
     */
    @Override
    public Result addProduct(Product product) {
        Code code = new Code();
        code.setType("CP");
        code.setText(code.getType() + "%s%s");
        String cpId = randomGenerateUtil.nextSerialNumber(code);
        product.setProductCode(cpId);
        product.setCurrentInventory(product.getInitialInventory());
        productMapper.insert(product);
        return Result.success(200, "seccess", product.getProductId());
    }

    /**
     * 根据仓库id获取库存
     * @param wId
     * @return
     */
    @Override
    public List<Product> selectProductById(Integer wId) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("warehouse_id", wId);
        return productMapper.selectList(queryWrapper);
    }

    /**
     * 获取所有库存
     * @param map
     * @return
     */
    @Override
    public List<Product> selectProductAll(Map<String, Object> map) {
        return productMapper.selectProductAll(map);
    }

    /**
     * 根据id删除产品
     * @param productId
     * @return
     */
    @Override
    public boolean delProductById(Integer productId) {
        List<PurchaseDetail> list = purchaseDetailMapper.selectPurchaseDetailById(productId);
        if (list == null || list.isEmpty()) {
            return false;
        }
        return productMapper.deleteById(productId) > 0;
    }

}
